// pages/detail/detail.js
const util = require('../../utils/util.js')
const api = require('../../utils/api.js')
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    product: [],
    pid: 0,
    swiperCurrent: 0,
    show_gg: false,
    ggchoose: '请选择规格数量',
    ggchoosed: '',
    buyNumber: 1,
    buyNumMin: 1,
    buyNumMax: 0,
    selectedSku: {},
    selectedSku: null,

    favicon: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    if (options.pid) {
      that.setData({
        pid: options.pid
      })
      that.getDetail();
    } else {
      util.showErrorToast("请输入商品ID")
      wx.navigateBack({})
    }
    if (options.show_gg) {
      that.setData({
        show_gg: options.show_gg
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.gohomeTop) {
      this.setData({
        top: app.globalData.gohomeTop
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '娜美达-' + this.data.product.title,
      path: '/pages/detail/detail?pid=' + this.data.product.id,
    }
  },
  setTouchMove: function (e) {
    var that = this;
    if (e.touches[0].clientY < 500 && e.touches[0].clientY > 0) {
      that.setData({
        top: e.touches[0].clientY
      })
      app.globalData.gohomeTop = e.touches[0].clientY
    }
  },
  //是否被收藏
  isFavored: function () {
    let that = this
    util.requestByToken(api.IsFavoredUrl + that.data.pid,{},'get',false).then(res => {
      if (res.status == 'success') {
        that.setData({
          favicon: res.data.favored ? 1 : 0,
        })
      }
    })
  },
  // 获取详情
  getDetail: function () {
    wx.showToast({
      title: '加载中..',
      icon: 'none',
    })
    let that = this
    let url = api.ProductDetailUrl + that.data.pid
    util.request(url).then(function (res) {
      wx.hideToast()
      if (res.status == 'success') {
        that.setData({
          product: res.data.product,
          buyNumMax: res.data.product.stock,
          buyNumber: res.data.product.stock > 0 ? 1 : 0,
        })
        that.isFavored()
        wx.hideLoading()
      } else {
        if (typeof (res.data) == 'string') {
          util.showErrorToast(res.data);
        } else {
          util.showErrorToast("错误，请重试");
        }
      }
    })
  },
  swiperChange: function swiperChange(e) {
    this.setData({
      swiperCurrent: e.detail.current
    });
  },

  // 打开规格dialog
  openPopup: function openPopup(e) {
    this.setData({
      show_gg: true
    });
  },
  // 点击遮罩关闭dialog
  toggleDialog() {
    this.setData({
      show_gg: !this.data.show_gg
    });
  },
  //规格选择弹窗
  labelItemTap: function labelItemTap(e) {
    var that = this;
    var childs = that.data.product.spec_info[e.currentTarget.dataset.specindex];//获取点击的规格组
    for (var i = 0; i < childs.length; i++) {
      that.data.product.spec_info[e.currentTarget.dataset.specindex][i].active = false;
    }
    that.data.product.spec_info[e.currentTarget.dataset.specindex][e.currentTarget.dataset.specchildindex].active = true;
    var needSelectNum = that.data.product.spec_info.length;
    var curSelectNum = 0;
    var specChildIds = "";
    var specChildNames = "";
    for (var i = 0; i < that.data.product.spec_info.length; i++) {
      childs = that.data.product.spec_info[i];
      for (var j = 0; j < childs.length; j++) {
        if (childs[j].active) {
          curSelectNum++;
          specChildIds = specChildIds + childs[j].spec.name + ":" + childs[j].id + ",";
          specChildNames = specChildNames + childs[j].spec.title + ":" + childs[j].item + " ";
        }
      }
    }
    var canSubmit = false;
    if (curSelectNum == needSelectNum) {
      canSubmit = true
      let url = api.GetSkuUrl
      util.request(url, {
        product_id: that.data.product.id,
        spec_child_ids: specChildIds,
      }).then(function (res) {
        if (res.status == 'success') {
          console.log
          if (!res.data.sku) {
            util.showErrorToast("sku已删除");
          }
          else {
            that.setData({
              selectedSku: res.data.sku,
              buyNumMax: res.data.sku.stock,
              buyNumber: res.data.sku.stock > 0 ? 1 : 0,
            });
          }
        } else {
          if (typeof (res.data) == 'string') {
            util.showErrorToast(res.data);
          } else {
            util.showErrorToast("错误，请重试");
          }
        }
      })
    }
    that.setData({
      product: that.data.product,
      canSubmit: canSubmit,
      specChildNames: specChildNames
    });
  },
  //数量减少
  numJianTap: function numJianTap() {
    if (this.data.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      });
    }
  },
  // 数量增加
  numJiaTap: function numJiaTap() {
    if (this.data.buyNumber < this.data.buyNumMax) {
      var currentNum = this.data.buyNumber;
      currentNum++;
      this.setData({
        buyNumber: currentNum
      });
    }
  },
  addToCart: function () {
    wx.showToast({
      title: '添加购物车...',
      icon: 'none',
    })
    let that = this
    if (that.data.canSubmit) {
      let url = api.AddCartItemsUrl
      util.requestByToken(url, {
        sku_id: that.data.selectedSku.id,
        amount: that.data.buyNumber,
      }, 'POST').then(function (res) {
        if (res.status == 'success') {
          wx.showToast({
            title: '添加成功',
            icon: 'none',
          })
          wx.hideLoading()
        } else {
          if (typeof (res.data) == 'string') {
            util.showErrorToast(res.data);
          } else {
            util.showErrorToast("错误，请重试");
          }
        }
      })
    } else {
      util.showErrorToast("选择规格");
    }
  },
  //到购物袋
  goShoppingBag: function () {
    wx.switchTab({
      url: '/pages/cart/cart',
    })
  },
  // 弹窗购买按钮
  goBuy: function () {
    let that = this
    if (that.data.canSubmit) {
      app.checkLogin().then(res => {
        wx.navigateTo({
          url: '/pages/orderConfirm/orderConfirm?skuid=' + that.data.selectedSku.id + '&amount=' + that.data.buyNumber
        })
        //goto购买页面
      }).catch(res => {
        util.showErrorToast("登录失败");
      })
    } else {
      util.showErrorToast("选择规格");
    }
  },
  goback: function () {
    wx.navigateBack({

    })
  },


  // 收藏按钮
  collect_tap: function () {
    let that = this
    let url = api.FavorUrl + that.data.pid + '/favorite'
    let method = 'POST'
    if (that.data.favicon == 1) {
      url = api.DisFavorUrl + that.data.pid + '/favorite'
      method = 'DELETE'
    }
    util.requestByToken(url, {}, method).then(res => {
      if (res.status == 'success') {
        that.setData({
          favicon: res.data.favored ? 1 : 0,
        })
      } else {
        if (typeof (res.data) == 'string') {
          util.showErrorToast(res.data);
        } else {
          util.showErrorToast("错误，请重试");
        }
      }
    })
  }

})